package com.tsd.core.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.awt.image.BufferedImage;
import java.util.Hashtable;

/**
 * @author zsy
 */
public class QrCodeUtils {

    /**
     * 生成二维码
     *
     * @param contents 二维码的内容
     * @param width    二维码图片宽度
     * @param height   二维码图片高度
     * @author nicky.ma
     * @date 2019年6月11日下午4:39:16
     */
    public static BufferedImage createQrCodeBufferdImage(String contents, int width, int height) throws WriterException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BufferedImage image = null;
        BitMatrix bitMatrix = new MultiFormatWriter().encode(
                contents, BarcodeFormat.QR_CODE, width, height, hints);
        image = toBufferedImage(bitMatrix);
        return image;
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

}
